package com.codeerror.demo.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.codeerror.demo.R;
import com.codeerror.demo.bean.WordsBgBean;

import org.raphets.roundimageview.RoundImageView;

import java.util.List;

public class WordsBgSelectRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final List<WordsBgBean> bgList;
    private OnImageSelectListener onImageSelectListener;
    private final int curSelectedBg;
    private RoundImageView lastIv; // 上一个被选择的ImageView
    private WordsBgBean lastBean;

    public WordsBgSelectRecyclerAdapter(List<WordsBgBean> bgList, int curSelectedBg) {
        this.bgList = bgList;
        this.curSelectedBg = curSelectedBg;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_recycler_words_bg_img, parent, false);
        return new RecyclerView.ViewHolder(view) {};
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        RoundImageView iv = (RoundImageView) holder.itemView;
        WordsBgBean bean = bgList.get(position);
        iv.setImageResource(bean.getBgId());
        // 设置选中与被选中
        iv.setBorderColor(bean.isSelected() ? R.color.teal_200 : 0);
        // 设置初始时已选中的背景
        if (bean.getBgId() == curSelectedBg){
            iv.setBorderColor(R.color.teal_200);
            lastIv = iv;
            lastBean = bean;
        }
        holder.itemView.setOnClickListener(view -> {
            if (lastIv != null && lastBean != null){
                lastIv.setBorderColor(0);
                lastBean.setSelected(false);
            }
            iv.setBorderColor(R.color.teal_200);
            bean.setSelected(true);
            lastIv = iv;
            lastBean = bean;
            onImageSelectListener.onSelectImage(bgList.get(position).getBgId());
        });
    }

    @Override
    public int getItemCount() {
        return bgList.size();
    }

    public void setOnImageSelectListener(OnImageSelectListener onImageSelectListener) {
        this.onImageSelectListener = onImageSelectListener;
    }

    public interface OnImageSelectListener{
        /**
         * 获取选择的图片id
         */
        void onSelectImage(int bgId);
    }
}
